Answer:

int factorial( int N )
{
  if ( N == 0 )
  
    return 1;
    
  else
  
    return N * factorial( N-1 );
}

Dynamic Thinking

activation chain

 

If you have a correct math-like definition of what you want to do, then transforming it into a Java method is almost mechanical.

But, you can also think about what happens as the method runs. This is a dynamic view of recursion. The diagram shows the how the activation chain grows as the method executes.

Each activation except the base case requires another activation. This is because the statement return n * factorial( N-1 ) needs a value for factorial( N-1 ) before the multiplication can be done. (Click on the diagram to see the activation chain grow.)

int factorial( int N )
{
  if ( N == 0 )
    return 1;
  else
    return N * factorial( N-1 ) ;
}

When the base case is reached, return values start being passed up the chain. After an activation has returned a value to its caller it is no longer active. The diagram shows this as a dotted circle.

QUESTION 4:

(Practice Dynamic Thinking: ) What would happen if factorial() were called with a parameter of -1?